<?php

namespace apiend\models;

use Yii;
use apiend\models\User;
use common\models\user\UserConnect;
use common\helpers\ArrayHelper;

/**
 * 第三方登录授权(自动注册)
 * ThirdPartyAuthForm
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ThirdPartyAutoAuthForm extends \common\base\Model {

    /**
     * @var string $client 外接第三方登录标识
     */
    public $client;

    /**
     * @var string $code 第三方接口返回的授权code
     */
    public $code;

    /**
     * @var $_user 用户模型
     */
    public $token = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['client', 'code'], 'required'],
            [['client'], 'in', 'range' => UserConnect::getAttributeMark('client'), 'message' => '{attribute}不在允许的授权范围内'],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function bind() {
        if (!$this->validate()) {
            $this->dumpError('授权参数校验失败');
        }

        $openid = null;
        $unionid = null;
        $authData = [];

        $synclogin = [];
        if ($this->client == UserConnect::CLIENT_WECHAT_OPEN) {
            $wechat = Yii::$app->wechat;
            $authData = $wechat->getOauth2AccessToken($this->code);
            //{ 
            //"access_token":"ACCESS_TOKEN", 
            //"expires_in":7200, 
            //"refresh_token":"REFRESH_TOKEN",
            //"openid":"OPENID", 
            //"scope":"SCOPE",
            //"unionid":"o6_bmasdasdsad6_2sgVt7hMZOPfL"
            //}
            $openid = ArrayHelper::getValue($authData, 'openid');
            $unionid = ArrayHelper::getValue($authData, 'unionid');
            $accessToken = ArrayHelper::getValue($authData, 'access_token');

            $synclogin = [
                'openid' => $openid,
                'unionid' => $unionid,
            ];
            if ($openid && $accessToken) {
                $userinfo = $wechat->getSnsUserInfo($openid, $accessToken);
//                {
//                "openid":"OPENID",
//                "nickname":"NICKNAME",
//                "sex":1,
//                "province":"PROVINCE",
//                "city":"CITY",
//                "country":"COUNTRY",
//                "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
//                "privilege":[
//                "PRIVILEGE1",
//                "PRIVILEGE2"
//                ],
//                "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
//                }
                if ($userinfo !== false) {
                    $avatar = ArrayHelper::getValue($userinfo, 'headimgurl');
                    $location = ArrayHelper::getValue($userinfo, 'country') . ArrayHelper::getValue($userinfo, 'province') . ArrayHelper::getValue($userinfo, 'city');
                    $gender = ArrayHelper::getValue($userinfo, 'sex');
                    $nickname = ArrayHelper::getValue($userinfo, 'nickname');

                    $synclogin = ArrayHelper::merge($synclogin, compact('nickname', 'gender', 'avatar', 'location'));
                }
            }


            //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        }
        $synclogin = array_filter($synclogin);
        if (empty($synclogin)) {
            $this->dumpError('第三方授权失败');
        }
        $synclogin['client'] = $this->client;
        $connect = UserConnect::syncLogin($synclogin);
        if (!isset($connect['status']) || !$connect['status']) {
            $this->dumpError($connect['msg']);
        }
        $meta = $connect['data'];

        $token = $this->token;
        if ($meta->mobile) {
            if (!$token->bindUser($meta->id)) {
                $this->dumpError('授权信息绑定失败');
            }
        } else {
            $token->user_id = 0;
            $token->save(false);
        }

        return $meta;
    }

}
